package day;

import java.util.Arrays;

/**
 * 517. 超级洗衣机
 */
public class D517 {
    public int findMinMoves(int[] machines) {
        int len = machines.length;
        int total = Arrays.stream(machines).sum();
        if (total % len != 0) {
            return -1;
        }
        //计算
        int size = total / len;
        int times = 0;
        while (true) {
            int[] optArray = new int[len];
            int sum = 0;
            //计算移动
            for (int i = 0; i < len; i++) {
                sum += machines[i];
                if (sum > (i + 1) * size) {
                    optArray[i] = 1;
                } else if (sum < (i + 1) * size) {
                    optArray[i + 1] = -1;
                }
            }
            if (!Arrays.stream(optArray).anyMatch(i -> i == 1 || i == -1)) {
                break;
            }
            //执行移动
            for (int i = 0; i < len; i++) {
                if (optArray[i] == 1) {
                    machines[i] -= 1;
                    machines[i + 1] += 1;
                } else if (optArray[i] == -1) {
                    machines[i] -= 1;
                    machines[i - 1] += 1;
                }
            }
            times++;
        }
        return times;
    }

    public static void main(String[] args) {
        int minMoves = new D517().findMinMoves(new int[]{4, 0, 0, 4});
        System.out.println(minMoves);
    }
}
